﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace CNative.Logging.Nlog
{
    public class FileLogger : ILogger
    {
        private string name;
        private NLog.Logger _logger;//= NLog.LogManager.GetCurrentClassLogger();

        public FileLogger(string _name)
        {
            name = _name;
            _logger = NLog.LogManager.GetLogger(_name);
            //try
            //{
            //    string isUseES = AppConfigurtaion.GetAppSettings("ESuri", "");
            //    if (!string.IsNullOrEmpty(isUseES))
            //    {
            //        var sss = new List<NLog.Config.LoggingRule>();
            //        for (var i = 0; i < NLog.LogManager.Configuration.LoggingRules.Count; i++)
            //        {
            //            var ru = NLog.LogManager.Configuration.LoggingRules[i];
            //            foreach (var tgg in ru.Targets)
            //            {
            //                if (tgg.Name.Contains("exceptionless"))
            //                {
            //                    sss.Add(ru);
            //                    break;
            //                }
            //            }
            //        }
            //        sss.ForEach(ru => NLog.LogManager.Configuration.LoggingRules.Remove(ru));
            //    }
            //}
            //catch (Exception ex) { _logger.Error(ex); }
        }
        public IDisposable BeginScope<TState>(TState state)
        {
            return null;
        }
        /// <summary>
        /// 判断是否开启记录
        /// </summary>
        public bool IsEnabled(LogLevel logLevel)
        {
            var convertLogLevel = ConvertLogLevel(logLevel);
            return _logger.IsEnabled(convertLogLevel);
        }
        /// <summary>
        /// 实现接口ILogger
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel"></param>
        /// <param name="eventId"></param>
        /// <param name="state"></param>
        /// <param name="exception"></param>
        /// <param name="formatter"></param>
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            var message = formatter(state, exception);

            if (String.IsNullOrEmpty(message) && exception == null)
                return;

            // Add event id, if available
            if (eventId.Id != 0)
                _logger.SetProperty("EventId", eventId.Id);

            _logger.SetProperty("TimeStamp", DateTime.UtcNow);
            if (state != null)
            {
                //if (state is IDictionary<string, object> stateProps)
                //{
                //    var ei = new MyLogEventInfo(ConvertLogLevel(logLevel), message, stateProps);

                //    _logger.Log(ei);
                //    return;
                //}
                if (state is IEnumerable<KeyValuePair<string, object>> stateProps)
                {
                    foreach (var prop in stateProps)
                    {
                        // Logging the message template is superfluous
                        _logger.SetProperty(prop.Key, prop.Value);
                    }
                }
                else
                {
                    // Otherwise, attach the entire object, using its type as the name
                    _logger.SetProperty("Tags", state.ToString());
                }
            }

            switch (logLevel)
            {
                case LogLevel.Critical://致命错误
                    _logger.Fatal(message);
                    break;
                case LogLevel.Debug:
                    _logger.Debug(message);
                    break;
                case LogLevel.Trace://追踪
                    _logger.Trace(message);
                    break;
                case LogLevel.Error:
                    _logger.Error(message);
                    break;
                case LogLevel.Information:
                    _logger.Info(message);
                    break;
                case LogLevel.Warning:
                    _logger.Warn(message);
                    break;
                default:
                    _logger.Info(message);
                    break;
            }
        }

        public NLog.LogLevel ConvertLogLevel(LogLevel logLevel)
        {
            switch (logLevel)
            {
                case LogLevel.Trace:
                    return NLog.LogLevel.Trace;
                case LogLevel.Debug:
                    return NLog.LogLevel.Debug;
                case LogLevel.Information:
                    return NLog.LogLevel.Info;
                case LogLevel.Warning:
                    return NLog.LogLevel.Warn;
                case LogLevel.Error:
                    return NLog.LogLevel.Error;
                case LogLevel.Critical:
                    return NLog.LogLevel.Fatal;
                case LogLevel.None:
                    return NLog.LogLevel.Off;
                default:
                    return NLog.LogLevel.Debug;
            }
        }
    }
}
